package org.jetnuke.modules.blog;

import java.util.GregorianCalendar;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.BlogCommentDAO;
import org.jetnuke.dao.BlogPostDAO;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.entities.BlogComment;
import org.jetnuke.entities.BlogPost;
import org.jetnuke.servlets.utilities.StringUtils;
import org.jetnuke.util.JetUtil;

public class SubmitComment implements IAction {
	String comment;
	int post_ID;
	String author;
	String url;
	String email;
	
	public void setEmail(String email) {
		this.email = StringUtils.filterText(email,true);
	}

	public void setAuthor(String author) {
		this.author = StringUtils.filterText(author,true);
	}

	public void setComment(String comment) {
		this.comment = StringUtils.filterText(comment,false);
	}

	public void setPost_ID(int post_ID) {
		this.post_ID = post_ID;
	}

	public void setUrl(String url) {
		this.url = StringUtils.filterText(url,true);
	}

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		BlogPostDAO bpm=DataAccessDriver.getInst().newBlogPostDAO();
		BlogPost bp=bpm.retrieveByPK(post_ID);
		if(bp.getID()!=post_ID)
			return null;//post_ID not valid!
		if(!"open".equals(bp.getCOMMENTSTATUS()))
			return null;//comment status not valid
		BlogCommentDAO bcm=DataAccessDriver.getInst().newBlogCommentDAO();
		BlogComment bc=new BlogComment();
		String ua=request.getHeader("user-agent");
		if(ua==null)
			ua="";
		String ip=request.getRemoteAddr();
		if(ip==null)
			ip="";
		bc.setAUTHOR(author);
		bc.setAGENT(ua);
		bc.setAUTHOR_URL(url);
		bc.setAUTHOR_EMAIL(email);
		bc.setAUTHOR_IP(ip);
		bc.setCONTENT(comment);
		bc.setDATE(new GregorianCalendar().getTime());
		bc.setPARENT(0);
		bc.setPOST_ID(post_ID);
		bc.setTYPE("comment");
		int uid=1;
		if(ui!=null)
			uid=ui.getID();
		String approved="0";
		//if(uid==bp.getAID())
		approved="1"; //TODO give more flexibility!!
		bc.setAPPROVED(approved);
		bc.setUSER_ID(uid);
		bcm.addNew(bc);
		JetUtil.redirect(vc,response,request.getContextPath()+"/do/blog/show_page?id="+post_ID+"&rand="+new Random().nextInt());
		return null;
	}

}
